package Aleehot100;

/**
 * ClassName: c051
 * Package: Aleehot100
 * Description:200 岛屿数量
 *
 * @Author BCXJ
 * @Create 2025/7/31 08:29
 * @Version 1.0
 * @Since 1.0
 */
public class c051 {
    public static void main(String[] args) {
        char[][] arr = {{'1', '1', '1', '1', '0'},
                {'1', '1', '0', '1', '0'},
                {'1', '1', '0', '0', '0'},
                {'0', '0', '0', '0', '0'}};

        System.out.println(numIslands(arr));
    }

    static int res = 0;


    /**
     * 本质的思路就是洪水填充
     * @param grid
     * @return
     */
    public static int numIslands(char[][] grid) {
        res = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == '1') {
                    dfs(grid, i, j);
                    res++;
                }

            }
        }

        return res;
    }

    private static void dfs(char[][] grid, int i, int j) {
        if ((i >= grid.length || i < 0) || (j < 0 || j > grid[0].length) || grid[i][j] != '1') {
            return;
        }
        grid[i][j] = '2';
        // 上
        dfs(grid, i - 1, j);
        // 下
        dfs(grid, i + 1, j);
        // 左
        dfs(grid, i, j - 1);
        // 右
        dfs(grid, i, j + 1);
    }

    /*
        static int res = 0;
    public static int numIslands(char[][] grid) {
        res = 0;

        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if(grid[i][j] == '1') {
                    dfs(grid, i, j);
                    res ++;
                }
            }
        }

        return res;
    }

    private static void dfs(char[][] grid, int i, int j) {
        if(i == -1 || i == grid.length || j == - 1 || j == grid[i].length || grid[i][j] != '1') {
            return;
        }
        grid[i][j] = '2';
        dfs(grid, i - 1, j);
        dfs(grid, i + 1, j);
        dfs(grid, i, j - 1);
        dfs(grid, i, j + 1);
    }
     */
}
